package com.huiyou.adminapi.service;


import com.huiyou.adminapi.common.RepeatException;
import com.huiyou.adminapi.common.model.SysRole;
import com.huiyou.adminapi.common.model.SysUser;
import com.huiyou.adminapi.repository.RoleRepository;
import com.huiyou.adminapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    @Autowired
    RoleRepository roleRepository;

    public Page<SysUser> findByNameContaining(String name, Pageable pageable) {
        return userRepository.findByNameContaining(name, pageable);
    }

    public SysUser findById(String id) {
        return userRepository.findById(id).get();
    }

    public void save(SysUser sysUser) {

        if (userRepository.findByAccount(sysUser.getAccount()).size() > 0) {
            throw new RuntimeException("用户名已存在!");
        }

        sysUser.setCreateTime(new Date().getTime());
        userRepository.save(sysUser);
    }

    public void edit(SysUser sysUser) {
        sysUser.setModifyTime(new Date().getTime());
        if (userRepository.findByAccountAndIdIsNot(sysUser.getAccount(), sysUser.getId()).size() > 0) {
            throw new RuntimeException("用户名已存在!");
        }
        userRepository.save(sysUser);
    }

    public List<SysRole> getRoleBindList(String userId) {
        return roleRepository.findByUserId(userId);
    }

    @Transactional
    public void saveRole(List<SysRole> roleList) {
        roleList.stream().forEach(item -> {
            roleRepository.save(item);
        });
    }

    @Transactional
    public void deleteRole(String userId) {
        roleRepository.deleteByUserId(userId);
    }

    @Transactional
    public SysUser userLogin(String account, String password) {
        SysUser sysUser = userRepository.findByAccountAndPasswordAndStatusIs(account, password, 0);
        if (!StringUtils.isEmpty(sysUser)) {
            sysUser.setLastTime(new Date().getTime());
            userRepository.save(sysUser);
        }
        return sysUser;
    }


}
